<template>
  <div class="home">
    <div class="box" v-for="(item, index) in qrList" :key="index">
      <div v-if="!item.boxShow">
        <!-- <div class="boxId">ID ：{{item.id}}</div> -->
        <div class="boxEdit" @mouseenter="editShowFn(item, index)">
          <span style="margin-left: 3px">...</span>
        </div>
        <div class="boxQr" id="boxQr">
          <vueQr :text="item.qrCodeUrl" :size="160" :margin="10"></vueQr>
        </div>
        <div class="boxName">{{ item.name }}</div>
        <div
          class="boxtitle"
          :style="{ color: item.status ? 'rgb(144,147,153)' : '' }"
        >
          创建者
        </div>
        <div
          class="boxApp"
          :style="{ color: item.status ? 'rgb(144,147,153)' : '' }"
          style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis"
        >
          {{ item.userName }}
        </div>
        <div
          class="boxtitle1"
          :style="{ color: item.status ? 'rgb(144,147,153)' : '' }"
        >
          分账规则
        </div>
        <div
          class="boxtcreateId"
          :style="{ color: item.status ? 'rgb(144,147,153)' : '' }"
          style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis"
        >
          {{ item.ruleName }}
        </div>
        <div
          class="boxtitle2"
          :style="{ color: item.status ? 'rgb(144,147,153)' : '' }"
        >
          支付渠道
        </div>
        <div
          class="boxchannel"
          :style="{ color: item.status ? 'rgb(144,147,153)' : '' }"
          style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis"
        >
          {{
            item.preChannel == "ada"
              ? "汇付"
              : item.preChannel == "direct"
              ? "(微信/支付宝)直连"
              : ""
          }}
        </div>
        <el-button
          style="width: 237px"
          class="boxButton"
          :type="!item.status ? 'primary' : 'info'"
          :disabled="item.status ? true : false"
          @click="downloadClick($event)"
          v-throttle="1000"
          >下载</el-button
        >
      </div>
      <div class="editBox" v-if="item.editShow" @mouseleave="editShowFn1(item)">
        <div
          class="editBoxOn"
          v-if="item.status"
          @click="editFn('edit', item, 0)"
        >
          <img
            src="@/assets/imgs/setting/on.png"
            alt=""
            style="margin-top: 7px"
          />
          <br />
          <br />
          <div v-if="item.status">启用</div>
        </div>
        <div class="editBoxOn" v-if="!item.status" @click="editFn('on', item)">
          <img
            src="@/assets/imgs/setting/off.png"
            alt=""
            style="margin-top: 7px"
          />
          <br />
          <br />
          <div v-if="!item.status">停用</div>
        </div>

        <div class="editBoxEdit" @click="editFn('edit', item)">
          <img
            src="@/assets/imgs/setting/edit-fill.png"
            alt=""
            style="margin-top: 7px"
          />
          <br />
          <br />
          <div>编辑</div>
        </div>
        <div class="editBoxDel" @click="editFn('del', item)">
          <img
            src="@/assets/imgs/setting/del.png"
            alt=""
            style="margin-top: 7px"
          />
          <br />
          <br />
          <div>删除</div>
        </div>
      </div>
      <div v-if="item.boxShow">
        <el-form
          :model="editForm"
          :rules="rules"
          ref="editForm"
          label-width="0px"
        >
          <div class="creatTitle">编辑</div>
          <div class="creatName">二维码名称</div>
          <el-form-item prop="name" label-width="28px">
            <div style="margin-top: 15px">
              <el-input
                v-model="editForm.name"
                style="width: 240px; margin-left: 2px"
                placeholder="请输入二维码名称"
                maxlength="12"
                show-word-limit
              ></el-input>
            </div>
          </el-form-item>
          <div class="createId">分账规则</div>
          <el-form-item prop="createId" label-width="28px">
            <div style="margin-top: 15px">
              <el-select
                style="width: 240px; margin-left: 2px"
                v-model="editForm.createId"
                placeholder="请选择分账规则名称"
                clearable
              >
                <el-option
                  v-for="item in caseAccounList"
                  :key="item.id"
                  :label="item.ruleName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <div class="channel">支付渠道</div>
          <el-form-item prop="preChannel" label-width="28px">
            <div style="margin-top: 15px">
              <el-select
                style="width: 240px; margin-left: 2px"
                v-model="editForm.preChannel"
                placeholder="请选择支付渠道"
                clearable
              >
                <el-option label="汇付" value="ada" key="ada"></el-option>
                <el-option
                  label="(微信/支付宝)直连"
                  value="direct"
                  key="direct"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
          <div class="creatButton">
            <el-button @click="editBoxFn(item)">取消</el-button>
            <el-button type="primary" @click="editSubmit(item, 'editForm')"
              >提交</el-button
            >
          </div>
        </el-form>
      </div>
    </div>
    <div class="creatBox">
      <div v-if="!creatshow" @click="creatShow">
        <div class="creaticon">
          <i class="el-icon-film"></i>
        </div>
        <div class="creatText">创建二维码</div>
      </div>
      <div v-if="creatshow">
        <div class="creatTitle">新建</div>
        <el-form :model="form" :rules="rules" ref="form">
          <div class="creatName">二维码名称</div>
          <el-form-item prop="name" label-width="28px">
            <div style="margin-top: 15px">
              <el-input
                v-model="form.name"
                style="width: 240px; margin-left: -28px"
                placeholder="请输入二维码名称"
                maxlength="12"
                show-word-limit
              ></el-input>
            </div>
          </el-form-item>
          <div class="createId">分账规则</div>
          <el-form-item prop="createId" label-width="28px">
            <div style="margin-top: 15px">
              <el-select
                style="width: 240px; margin-left: -28px"
                v-model="form.createId"
                placeholder="请选择分账规则名称"
                clearable
              >
                <el-option
                  v-for="item in caseAccounList"
                  :key="item.id"
                  :label="item.ruleName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <div class="channel">支付渠道</div>
          <el-form-item prop="preChannel" label-width="28px">
            <div style="margin-top: 15px">
              <el-select
                style="width: 240px; margin-left: -28px"
                v-model="form.preChannel"
                placeholder="请选择支付渠道"
                clearable
              >
                <el-option
                  label="汇付"
                  value="ada"
                  key="ada"
                  v-if="
                    payChannel.filter((item) => item.value == 'ada').length > 0
                  "
                ></el-option>
                <el-option
                  label="(微信/支付宝)直连"
                  value="direct"
                  key="direct"
                  v-if="
                    payChannel.filter((item) => item.value == 'ali').length > 0 &&
                    payChannel.filter((item) => item.value == 'wechat').length > 0
                  "
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
          <div class="creatButton">
            <el-button @click="creatShow('form')">取消</el-button>
            <el-button type="primary" @click="creatSubmit('form')"
              >提交</el-button
            >
          </div>
        </el-form>
      </div>
    </div>
    <codeDialogVue
      codeId="1"
      :type="codeType"
      :codeDialog.sync="codeDialog"
      @codeState="codeStateFn"
    />
  </div>
</template>

<script>
import codeDialogVue from "@/components/codeDialog.vue";
import { getUserInfo } from "@/utils/public";
import vueQr from "vue-qr";
export default {
  name: "collectionQR",
  components: {
    vueQr,
    codeDialogVue,
  },
  data() {
    return {
      payChannel: [],
      codeItem: null,
      codeType: "",
      codeDialog: false,
      rules: {
        name: [
          { required: true, message: "请输入二维码名称", trigger: "change" },
          {
            pattern: /^(?!\s+).*(?<!\s)$/,
            message: "格式有误",
            trigger: "change",
          },
        ],
        preChannel: [
          { required: true, message: "请选择支付渠道", trigger: "change" },
        ],
      },
      caseAccounList: [],
      creatshow: false,
      form: {
        name: "",
        createId: "",
        preChannel: "",
      },
      editForm: {
        name: "",
        createId: "",
        preChannel: "",
      },
      qrList: [],
      statusType: 2,
    };
  },
  created() {
    this.getList();
    this.getRuleList();
    this.getChannelList();
  },
  watch: {
    "$store.state.testLine": {
      handler() {
        if (this.$route.name == this.$options.name) {
          this.getList();
        }
      },
    },
    deep: true,
  },
  methods: {
    getUserInfo,
    getChannelList() {
      this.$http.get("/api/dict/channelList").then((res) => {
        if (res.code === "0000") {
          var a = [{ label: "所有", value: "" }];
          var b = a.concat(res.data);
          this.payChannel = b;
          console.log(this.payChannel);
        }
      });
    },
    codeStateFn(val) {
      if (val) {
        if (this.codeType == "SMS_BUSINESS_STOP_QRCODE") {
          this.onOffFn(this.codeItem);
        } else if (this.codeType == "SMS_BUSINESS_EDIT_QRCODE") {
          this.editSubmit1(this.codeItem);
        } else if (this.codeType == "SMS_BUSINESS_DELETE_QRCODE") {
          this.delFn(this.codeItem);
        }
      }
    },
    downloadClick(e) {
      // 先找到canvas节点下的二维码图片
      var img = e.target.parentNode.parentNode.getElementsByTagName("img");
      var name =
        e.target.parentNode.parentNode.getElementsByClassName("boxName")[0]
          .innerText;

      // 创建一个a节点
      const a = document.createElement("a");
      // 设置a的href属性将canvas变成png格式
      const imgURL = img[0].src;
      const ua = navigator.userAgent;
      if (ua.indexOf("Trident") !== -1 && ua.indexOf("Windows") !== -1) {
        // IE内核 并且  windows系统 情况下 才执行;
        var bstr = atob(imgURL.split(",")[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        const blob = new Blob([u8arr]);

        window.navigator.msSaveOrOpenBlob(blob, "下载" + "." + "png");
      } else if (ua.indexOf("Firefox") > -1) {
        // 火狐兼容下载
        const blob = this.base64ToBlob(imgURL); //new Blob([content]);
        const evt = document.createEvent("HTMLEvents");
        evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        a.download = " "; //下载图片名称，如果填内容识别不到，下载为未知文件，所以我这里就不填为空
        a.href = URL.createObjectURL(blob);
        a.dispatchEvent(
          new MouseEvent("click", {
            bubbles: true,
            cancelable: true,
            view: window,
          })
        );
      } else {
        // 谷歌兼容下载
        a.href = imgURL;
        // 设置下载文件的名字
        a.download = name + "二维码";
        // 点击
        a.click();

        this.$message({
          message: "下载成功，已保存到桌面",
          type: "success",
        });
      }
    },

    // base64转blob
    base64ToBlob(code) {
      let parts = code.split(";base64,");
      let contentType = parts[0].split(":")[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], {
        type: contentType,
      });
    },
    getRuleList() {
      this.$http.post("/api/settle/rules/getRuleList").then((res) => {
        if (res.code === "0000") {
          //console.log(res.data);
          this.caseAccounList = res.data;
          this.caseAccounList.map((item) => console.log(item.id));
        }
      });
    },
    getList() {
      this.$http
        .post("/api/merchant/qrcode/getMemberQrcodeList")
        .then((res) => {
          if (res.code === "0000") {
            let qrList1 = res.data;
            qrList1.forEach((e) => {
              e.editShow = false;
              e.boxShow = false;
            });
            this.qrList = qrList1;
          }
        });
    },
    editBoxFn(item) {
      this.qrList.forEach((e) => {
        if (e == item) {
          e.boxShow = false;
          e.editShow = false;
        }
      });
    },
    editSubmit(item, formName) {
      //console.log(this.statusType);
      this.$refs[formName][0].validate((valid) => {
        if (valid) {
          if (getUserInfo().checkFlag) {
            this.editSubmit1(item);
          } else {
            this.codeType = "SMS_BUSINESS_EDIT_QRCODE";
            this.codeDialog = true;
            this.codeItem = item;
          }
        } else {
          return false;
        }
      });
    },
    editSubmit1(item) {
      this.$http
        .post("/api/merchant/qrcode/updateMemberQrcode", {
          id: item.id,
          name: this.editForm.name,
          preChannel: this.editForm.preChannel,
          settleRuleId: this.editForm.createId,
          status: this.statusType == 0 ? this.statusType : null,
        })
        .then((res) => {
          if (res.code === "0000") {
            this.$message.success("编辑成功！");
            this.getList();
          }
        });
    },
    editFn(val, item, type) {
      //console.log(type);
      if (val == "on") {
        if (getUserInfo().checkFlag) {
          this.onOffFn(item);
        } else {
          this.codeItem = item;
          this.codeDialog = true;
          this.codeType = "SMS_BUSINESS_STOP_QRCODE";
        }
      } else if (val == "del") {
        if (getUserInfo().checkFlag) {
          this.delFn(item);
        } else {
          this.codeItem = item;
          this.codeDialog = true;
          this.codeType = "SMS_BUSINESS_DELETE_QRCODE";
        }
      } else {
        this.editForm.name = item.name;
        this.editForm.createId = item.settleRuleId;
        this.editForm.preChannel = item.preChannel;
        this.qrList.forEach((e) => {
          e.boxShow = false;
          e.editShow = false;
          if (e == item) {
            e.boxShow = true;
            this.statusType = type !== undefined ? type : 1;
          }
        });
      }
    },
    delFn(item) {
      let that = this;
      that
        .$confirm(`确定删除该二维码?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          customClass: "confirm",
          type: "warning",
          center: true,
        })
        .then(() => {
          // var params = new FormData();
          // params.append("id", item.id);
          // let params = {
          //   id: item.id,
          // };
          that.$http
            .delete(`/api/merchant/qrcode/deleteMemberQrcode?id=${item.id}`)
            .then((res) => {
              if (res.code === "0000") {
                that.$message.success("删除成功！");
                that.getList();
              }
            });
        });
    },
    onOffFn(item) {
      let params = {
        id: item.id,
      };
      if (item.status) {
        // const params = new FormData();
        // params.append("id", item.id);
        // params.append("status", "0");
        params.status = "0";
        this.$http
          .post("/api/merchant/qrcode/updateMemberQrcodeStatus", params)
          .then((res) => {
            if (res.code === "0000") {
              this.$message.success("启用成功！");
              this.getList();
            }
          });
      } else {
        // const params = new FormData();
        // params.append("id", item.id);
        // params.append("status", "1");
        params.status = "1";
        this.$http
          .post("/api/merchant/qrcode/updateMemberQrcodeStatus", params)
          .then((res) => {
            if (res.code === "0000") {
              this.$message.success("禁用成功！");
              this.getList();
            }
          });
      }
    },
    editShowFn(item) {
      this.qrList.forEach((e) => {
        if (e == item) {
          e.editShow = true;
        }
      });
      //console.log(this.qrList[0].editShow);
    },
    editShowFn1(item) {
      this.qrList.forEach((e) => {
        if (e == item) {
          e.editShow = false;
        }
      });
    },
    downloadFn(item) {
      if (item.status) {
        this.$message.warning("二维码已停用！");
      } else {
        this.$message.success("已添加到下载中心！");
      }
    },
    creatSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http
            .post("/api/merchant/qrcode/createMemberQrcode", {
              name: this.form.name,
              preChannel: this.form.preChannel,
              settleRuleId: this.form.createId,
            })
            .then((res) => {
              if (res.code === "0000") {
                this.$message.success("创建成功！");
                this.getList();
                this.creatshow = false;
              }
            });
        } else {
          return false;
        }
      });
    },
    creatShow() {
      this.form = {};
      this.creatshow = !this.creatshow;
    },
  },
};
</script>
<style scoped lang="scss">
.home {
  width: 100%;
  display: flex;
  justify-content: start;
  flex-wrap: wrap;
  .box {
    min-width: 296px;
    width: 296px;
    height: 464px;
    background: #ffffff;
    border-radius: 10px;
    border: 1px solid #e5e5e5;
    margin-right: 38px;
    margin-bottom: 20px;
    position: relative;
    .creatTitle {
      width: 70px;
      margin: 0 auto;
      margin-top: 24px;
      font-size: 28px;
      font-family: PingFangSC-Light, PingFang SC;
      font-weight: 500;
      color: #1f1d1d;
    }
    .creatName {
      width: 120px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      line-height: 20px;
      margin-left: 30px;
      margin-top: 26px;
    }
    .createId {
      width: 120px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      line-height: 20px;
      margin-left: 30px;
      margin-top: 26px;
    }
    .channel {
      width: 120px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      line-height: 20px;
      margin-left: 30px;
      margin-top: 26px;
    }
    .creatButton {
      width: 292px;
      position: absolute;
      bottom: 30px;
      left: 22px;
      .el-button {
        width: 120px;
      }
    }
    .boxId {
      width: 85px;
      height: 17px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #bfbfbf;
      line-height: 17px;
      position: absolute;
      left: 30px;
      top: 20px;
    }
    .boxEdit {
      cursor: pointer;
      width: 19px;
      height: 19px;
      line-height: 9px;
      border-radius: 50%;
      border: 1px solid #bfbfbf;
      color: #bfbfbf;
      opacity: 0.5;
      position: absolute;
      right: 26px;
      top: 20px;
    }
    .boxQr {
      position: absolute;
      left: 66px;
      top: 62px;
      width: 164px;
      height: 164px;
      border: 1px solid #f0f0f0;
    }
    .boxName {
      width: 216px;
      height: 50px;
      text-align: center;
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 600;
      color: #1d1c1c;
      line-height: 25px;
      position: absolute;
      left: 40px;
      top: 241px;
    }
    .boxtitle {
      width: 42px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #869daa;
      line-height: 20px;
      position: absolute;
      left: 30px;
      top: 291px;
    }
    .boxApp {
      text-align: right;
      width: 160px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #4f595f;
      line-height: 20px;
      position: absolute;
      right: 27px;
      top: 291px;
    }
    .boxtitle1 {
      width: 56px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #869daa;
      line-height: 20px;
      position: absolute;
      left: 30px;
      top: 321px;
    }
    .boxtcreateId {
      width: 160px;
      text-align: right;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #4f595f;
      line-height: 20px;
      position: absolute;
      right: 27px;
      top: 321px;
    }
    .boxtitle2 {
      width: 56px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #869daa;
      line-height: 20px;
      position: absolute;
      left: 30px;
      top: 351px;
    }
    .boxchannel {
      text-align: right;
      width: 160px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #4f595f;
      line-height: 20px;
      position: absolute;
      right: 27px;
      top: 351px;
    }
    .boxButton {
      position: absolute;
      left: 30px;
      bottom: 30px;
    }
    .editBox {
      position: absolute;
      right: 0;
      top: 0;
      width: 158px;
      height: 460px;
      background: #fffffff8;
      box-shadow: -6px 0px 14px 0px rgba(0, 0, 0, 0.05);
      border-radius: 10px;
      opacity: 1;
      .editBoxOn {
        cursor: pointer;
        position: relative;
        left: 62px;
        top: 65px;
        text-align: center;
        width: 36px;
        height: 36px;
        background: #25b5d9;
        border-radius: 50%;
      }
      .editBoxEdit {
        cursor: pointer;

        position: relative;
        left: 62px;
        top: 170px;
        text-align: center;
        width: 36px;
        height: 36px;
        border-radius: 50%;

        background: #ee8f24;
      }
      .editBoxDel {
        cursor: pointer;

        position: relative;
        left: 62px;
        top: 284px;
        text-align: center;
        width: 36px;
        height: 36px;
        border-radius: 50%;

        background: #e23d28;
      }
    }
  }
  .box:hover {
    border: 1px solid #03bfc6;
  }
  .creatBox {
    width: 296px;
    height: 464px;
    background: #ffffff;
    border-radius: 10px;
    border: 1px dashed #03bfc6;
    margin-right: 38px;
    margin-bottom: 20px;
    position: relative;
    text-align: center;
    .creaticon {
      cursor: pointer;
      margin-top: 180px;
      position: relative;
      font-size: 18px;
      color: #03bfc6;
    }
    .creatText {
      cursor: pointer;
      margin-top: 10px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 500;
      color: #03bfc6;
    }
    .creatTitle {
      margin-top: 24px;
      font-size: 28px;
      font-family: PingFangSC-Light, PingFang SC;
      font-weight: 500;
      color: #1f1d1d;
    }
    .creatName {
      width: 120px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      line-height: 20px;
      margin-left: 6px;
      margin-top: 26px;
    }
    .createId {
      width: 120px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      line-height: 20px;
      margin-left: 0px;
      margin-top: 26px;
    }
    .channel {
      width: 120px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      line-height: 20px;
      margin-left: 0px;
      margin-top: 26px;
    }
    .creatButton {
      width: 292px;
      position: absolute;
      bottom: 30px;
      margin: 0 auto;
      .el-button {
        width: 120px;
      }
    }
  }
}
</style>
